import { utils, writeFile } from 'xlsx';
import { ElMessage,ElMessageBox } from 'element-plus'
// 时间戳格式化
export function date(timeStamp, format = 'yyyy-MM-dd HH:mm:ss') {
    const date = new Date(timeStamp * 1000)
    const year = String(date.getFullYear())       // 2025
    const month = String(date.getMonth() + 1).padStart(2, '0')  // 06
    const day = String(date.getDate()).padStart(2, '0')         // 12
    const hour = String(date.getHours()).padStart(2, '0')       // 10
    const minute = String(date.getMinutes()).padStart(2, '0')   // 27
    const second = String(date.getSeconds()).padStart(2, '0')   // 42
  
    const map = {
      yyyy: year,
      yy: year.slice(-2), // 取后两位，如 25
      MM: month,
      M: month.replace(/^0/, ''), // 去掉前导 0，如 6
      dd: day,
      d: day.replace(/^0/, ''),
      HH: hour,
      H: hour.replace(/^0/, ''),
      mm: minute,
      m: minute.replace(/^0/, ''),
      ss: second,
      s: second.replace(/^0/, '')
    }
  
    // 替换所有匹配的占位符
    return format.replace(/(yyyy|yy|M+|MM|dd|d+|HH|h+|mm|m+|ss|s+)/g, (match) => {
      return map[match] || ''
    })
  }

// 把文件按二进制读取
export function readFile(file){
    return new Promise(resolve => {
        let reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = ev => {
            resolve(ev.target.result);
        };
    })
}
// 设置异步间隔延迟
export function delay(interval){
    return new Promise(resolve => {
        let timer = setTimeout(_ => {
            clearTimeout(timer);
            resolve();
        },interval)
    })
}
/**
 * 数据导出为excle表格
 * @param {Object} data 要导出的数据Object
 * @param {String} name 导出表格名称
 */
export function getExcle(data, name='导出表格'){
    let sheet = utils.json_to_sheet(data),
    book = utils.book_new();
    utils.book_append_sheet(book, sheet, "导出商品");
    writeFile(book, `${name + new Date().getTime()}.xls`);
}
export const showError = (msg = '操作失败，请重试') => {
    ElMessage.error(msg)
  }
  
  export const showSuccess = (msg = '操作成功') => {
    ElMessage.success(msg)
  }
  // 确认框（用于删除等操作）
export const showConfirm = async (content = '您确定要执行此操作吗？', title = '提示') => {
    try {
      await ElMessageBox.confirm(content, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      });
      return true;
    } catch (error) {
      // 用户点击取消或出现错误
      return false;
    }
  };

    

